import React, {useEffect} from 'react';
import {Table, Button, Tooltip, message} from 'antd';
import {
  DeleteOutlined,
  PlusCircleOutlined,
  TeamOutlined,
} from '@ant-design/icons';
import moment from 'moment';
import './index.less';
import '../assets/incofont.css';
import {useState} from 'react';
import AddToken from './components/AddToken';
import Authorization from './components/Authorization';
import {connect} from "dva";
import tokenManage from "@/models/tokenManage";

function UserPrivilege(props) {
  const [addModalVisible, setAddModalVisible] = useState(false);
  const [authVisible, setAuthVisible] = useState(false);
  const [options, setOptions] = useState([]);
  const [checkedOptions, setCheckedOptions] = useState([]);
  const [tokenId, setTokenId] = useState(0);
  const {tokenManage: {}, dispatch} = props;
  const [tableData, setTableData] = useState([]);

  function getAllTokens() {
    dispatch({
      type: "tokenManage/getAllTokens"
    }).then(res => {
      res.forEach((t) => t.expire > new Date().valueOf() ? t.state = '正常' : t.state = '已过期');
      console.log("Tokens", res);
      setTableData(res);
    });
  }

  useEffect(() => {
    console.log("组件加载时，运行一次该函数");
    getAllTokens();
  }, []);

  const columns = [
    {
      title: 'token-id',
      dataIndex: 'id',
      key: 'id',
      // width: "16%",
      render: (id, item) => {
        return <span style={{color: item.state === '正常' ? '#23d346' : 'red'}}>{id}</span>;
      },
    },
    {
      title: 'token',
      dataIndex: 'token',
      key: 'token',
      // width: "16%",
      render: (id, item) => {
        return <span style={{color: item.state === '正常' ? '#23d346' : 'red'}}>{id}</span>;
      },
    },
    {
      title: '描述',
      dataIndex: 'note',
      key: 'note',
      // width: '16%',
    },
    {
      title: '过期时间',
      key: 'expire',
      dataIndex: 'expire',
      // width: '16%',
      render: text => moment(text).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '创建时间',
      key: 'createTime',
      dataIndex: 'createTime',
      // width: '16%',
      render: text => moment(text).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '状态',
      dataIndex: 'state',
      key: 'state',
      // width: '16%',
      render: (state) => {
        return <span
          style={{background: state === '正常' ? '#23d346' : 'red', color: "white", borderRadius: "2px"}}>{state}</span>;
      },
    },
    {
      title: '操作',
      key: 'operation',
      render: (text, record) => (
        <div>
          <Tooltip placement="top" title="授权Token">
            <TeamOutlined className="oper-icon" style={{color: '#1890ff'}} onClick={() => auth(record)}/>
          </Tooltip>
          <Tooltip placement="top" title="删除">
            <DeleteOutlined className="oper-icon" style={{color: 'red'}} onClick={() => delToken(record)}/>
          </Tooltip>
        </div>
      ),
    },
  ];
  const data = [
    {
      id: 11111111111111111,
      describe: 'this is xiaozhang',
      overTime: 11111111111,
      createTime: 11111111111,
      state: '正常',
    },
    {
      id: 11111111111111111,
      describe: 'this is xiaozhang',
      overTime: 11111111111,
      createTime: 11111111111,
      state: '已过期',
    },
    {
      id: 11111111111111111,
      describe: 'this is xiaozhang',
      overTime: 11111111111,
      createTime: 11111111111,
      state: '已过期',
    },
  ];

  function handleAddToken() {
    setAddModalVisible(true);
  };

  function getAuthGroups(tokenId) {
    console.log("tokenId", tokenId);
    dispatch({
      type: "tokenManage/getAuthGroups",
      payload: {
        id: tokenId
      }
    }).then(res => {
      console.log("已授权", res);
      setCheckedOptions(res);
    })
  }


  function getAllApiGroups() {
    dispatch({
      type: "groupManage/getAll"
    }).then(res => {
      let ops = Array();
      res.forEach(t => ops.push({label: t.name, value: t.id}));
      console.log("ops", ops);
      setOptions(ops);
    });
  }

  function auth(token) {
    console.log(token);

    setTokenId(token.id);
    // 获取所有的api分组信息
    getAllApiGroups();
    // 获取已经授权的api分组id
    getAuthGroups(token.id);


    // TODO:get data from serve
    // const ops = [
    //   {label: '用户分组', value: 'ID1'},
    //   {label: '特殊分组', value: 'ID2'},
    //   {label: 'A类', value: 'ID3'},
    //   {label: '腾讯', value: 'ID4'},
    //   {label: '华为', value: 'ID5'},
    //   {label: 'ByteDance', value: 'ID6'}
    // ]
    // setOptions(ops);
    // setCheckedOptions(["ID1", "ID3", "ID6"]);
    setAuthVisible(true);
  }

  function delToken(token) {
    console.log("token", token);
    // TODP: send request to del the token with tokenId
    dispatch({
      type: "tokenManage/deleteToken",
      payload: {
        id: token.id
      }
    }).then(res => {
      getAllTokens();
    });
    message.success("成功删除Token:" + token.id);
  }

  return (
    <div className="data-resource">
      <h2 className="big-font">权限Token</h2>
      <div style={{marginBottom: '20px'}}>
        <Button className="btns" onClick={handleAddToken}>
          <PlusCircleOutlined style={{marginLeft: '-8px'}}/>
          新建Token
        </Button>
      </div>
      <h3 className="big-font">token列表</h3>
      <Table columns={columns} dataSource={tableData}/>
      {addModalVisible &&
      <AddToken setAddModalVisible={setAddModalVisible} addModalVisible={addModalVisible} getAllTokens={getAllTokens}/>}
      {authVisible && <Authorization
        visible={authVisible}
        setVisible={setAuthVisible}
        plainOptions={options}
        checkedOptions={checkedOptions}
        setCheckedOptions={setCheckedOptions}
        tokenId={tokenId}
        tokenManage={tokenManage}
        dispatch={dispatch}
        getAllTokens={getAllTokens}
      />}
    </div>
  );
}

export default connect(({tokenManage}) => ({tokenManage}))(UserPrivilege);
